﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using System.Reflection;
using System.IO;

namespace Masood.SharePoint.CodeGenerator
{
    public partial class frmSharePointXmlGenerator : Form
    {
        private StringBuilder fieldsXml;// = new StringBuilder();
        private StringBuilder ctXml;// = new StringBuilder();
        private StringBuilder fieldRefXml;// = new StringBuilder();

        public frmSharePointXmlGenerator()
        {
            InitializeComponent();
        }

        private void btnFieldsXml_Click(object sender, EventArgs e)
        {
            try
            {
                lblLoadingMsg.Text = "Please wait ...";
                Application.DoEvents();

                fieldsXml = new StringBuilder();
                fieldsXml.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>");
                fieldsXml.Append(@"<Elements xmlns=""http://schemas.microsoft.com/sharepoint/"">");
                StringBuilder choices = new StringBuilder();

                using (SPSite site = new SPSite(txtUrl.Text))
                {
                    foreach (SPField field in site.RootWeb.Fields)
                    {
                        if (field.Group.Equals(txtGroupName.Text))
                        {
                            choices = new StringBuilder();
                            if (field.TypeAsString == "Choice")
                            {
                                choices.Append("<CHOICES>");
                                SPFieldChoice choiceField = (SPFieldChoice)field;
                                foreach (var choice in choiceField.Choices)
                                    choices.AppendFormat("<CHOICE>{0}</CHOICE>", choice);

                                choices.Append("</CHOICES>");
                            }

                            fieldsXml.AppendFormat(Constants.Field, field.Id.ToString("B"),
                                                        field.Title,
                                                        field.Required,
                                                        field.EnforceUniqueValues.ToString(),
                                                        field.Group,
                                                        field.TypeAsString,
                                                        field.StaticName,
                                                        field.InternalName,
                                                        field.DefaultValue,
                                                        choices.ToString());
                            fieldsXml.Append(Environment.NewLine);
                            fieldsXml.Append(Environment.NewLine);
                        }
                    }

                    fieldsXml.Append("</Elements>");


                    txtXml.Text = "";
                    txtXml.Text = fieldsXml.ToString();

                    //Copy to clipboard
                    CopyToClipboard();

                    //MessageBox.Show("Done.");
                    lblLoadingMsg.Text = "Done. Below code has been copied to clipboard.";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception:" + ex.Message);
            }
        }

        private bool DoesExists(Guid fieldId, SPContentType parentContentType)
        {
            bool exists = false;
            try
            {
                SPFieldLink link = parentContentType.FieldLinks[fieldId];
                if (link != null)
                    exists = true;
            }
            catch (Exception ex)
            {
                exists = false;
            }

            return exists;
        }

        private void btnContentTypesXml_Click(object sender, EventArgs e)
        {
            try
            {
                lblLoadingMsg.Text = "Please wait...";
                Application.DoEvents();

                using (SPSite site = new SPSite(txtUrl.Text))
                {
                    ctXml = new StringBuilder();
                    ctXml.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>");
                    ctXml.Append(@"<Elements xmlns=""http://schemas.microsoft.com/sharepoint/"">");

                    //fieldsXml = new StringBuilder();

                    foreach (SPContentType contentType in site.RootWeb.ContentTypes)
                    {
                        fieldRefXml = new StringBuilder();

                        if (contentType.Group.Equals(txtGroupName.Text))
                        {
                            //SPContentTypeId contentTypeId = new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900778B4F21A8B34450B8B6EDAC72BFAE0C");
                            //SPContentType contentType = site.RootWeb.ContentTypes[contentTypeId];

                            ////SPContentTypeId parentContentTypeId = new SPContentTypeId("0x0100A187A58BA91DF147847D93FC19E89ED2");
                            SPContentType parentContentType = contentType.Parent; // site.RootWeb.ContentTypes[parentContentTypeId];

                            //SPField field = null;

                            ctXml.AppendFormat("<!--({0}) {1} -->", parentContentType.Name, parentContentType.Id);
                            ctXml.Append(Environment.NewLine);
                            ctXml.AppendFormat(Constants.ContentTypeString, contentType.Id.ToString(),
                                                         contentType.Name,
                                                         contentType.Description,
                                                         txtGroupName.Text);

                            fieldRefXml.Append("<FieldRefs>");
                            foreach (SPFieldLink fieldLink in contentType.FieldLinks)
                            {
                                if (!DoesExists(fieldLink.Id, parentContentType))
                                {
                                    fieldRefXml.AppendFormat(Constants.FieldRef, fieldLink.Id.ToString("B"), fieldLink.Name);
                                    fieldRefXml.Append(Environment.NewLine);                                    
                                }
                            }

                            fieldRefXml.Append("</FieldRefs>");
                            ctXml.Append(fieldRefXml.ToString());
                            ctXml.Append("</ContentType>");
                            ctXml.Append(Environment.NewLine);
                            ctXml.Append(Environment.NewLine);
                        }
                    }

                    ctXml.Append("</Elements>");

                    txtXml.Text = "";
                    txtXml.Text = ctXml.ToString();

                    //Copy to clipboard
                    CopyToClipboard();

                    //MessageBox.Show("Done.");
                    lblLoadingMsg.Text = "Done. Below code has been copied to clipboard.";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception:" + ex.Message);
            }
        }

        private void btnModuleSamples_Click(object sender, EventArgs e)
        {
            try
            {
                string assemblyPath = Assembly.GetExecutingAssembly().Location;
                string assemblyFolder = Path.GetDirectoryName(assemblyPath);
                string moduleSampleFilePath = Path.Combine(assemblyFolder, "module_sample.txt");

                StreamReader streamReader = File.OpenText(moduleSampleFilePath);
                txtXml.Text = streamReader.ReadToEnd();

                streamReader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception:" + ex.Message);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearResults();
        }

        private void btnCopyToClipboard_Click(object sender, EventArgs e)
        {
            CopyToClipboard();
        }

        private void CopyToClipboard()
        {
            Clipboard.SetDataObject(txtXml.Text);
        }

        private void ClearResults()
        {
            txtXml.Text = "";
        }
    }
}
